<admintpl file="header" />
<style type="text/css">
.pic-list li {
	margin-bottom: 5px;
}

input,select{
	z-index: 100!important;
}
.vip{
	color: #ea2935!important;
}
.desc {
	color: #838383;
	padding: 10px;
}
</style>
</head>
<body>
	<div class="wrap js-check-wrap">
		<ul class="nav nav-tabs">
			<li class="active"><a href="{:U('AdminSale/add',array('id'=>empty($item['id'])?'':$item['id']))}" target="_self">卡片消费</a></li>
		</ul>
		<div id="mask"></div>
		<form action="{:U('AdminSale/add_post')}" method="post" class="form-horizontal js-ajax-forms" onsubmit="return submitform();" enctype="multipart/form-data" onkeydown="if(event.keyCode==13){return false;}">
            <input type="hidden" name="force_price" id="force_price" value="">
			<div class="row-fluid">
				<div class="span9">
					<table class="table table-bordered">
						<tr>
						<th>卡号</th>
                            <td>
                                <input type="text" name="card_number" class="require" id="card_number" value="" style="width: 400px" placeholder="请输入卡号">
                                <span class="desc hand_input">请使用读卡机</span>
								<!-- <div class="div_quicksearch card_number_list">
									<input type="text" name="select_card_number" id="select_card_number" value="" placeholder="请输入会员卡号"/>
									<ul class="card_number_list quicksearch">
										<foreach name="card_list" item="citem">
											<li  onclick="quick_select('card_number','{$citem.number}')">{$citem.number}</li>
										</foreach>
										<li class="no_card_number">没找到数据</li>
									</ul>
								</div> -->
                            </td>
						</tr>
                        <tr>
                            <th>所属机构</th>
                            <td>
                                <input type="text" name="logistics_name" id="logistics_name" value="" style="width: 400px" readonly>
                                <input type="hidden" name="logistics_id" id="logistics_id">
                                <input type="hidden" name="is_vip" id="is_vip">
                            </td>
                        </tr>
                        <tr>
                            <th>卡内余额</th>
                            <td>
                                <input type="text" name="card_balance" id="card_balance" value="" style="width: 400px" readonly>
                            </td>
                        </tr>
						<tr>
							<th>选择商品</th>
							<td>
								<select name="sale_good_id" id="sale_good_id" style="width: 416px">
									<!-- <option value="">请选择商品</option> -->
									<foreach name="good_list" item="gitem">
										<option value="{$gitem.id}" >{$gitem.good_name}</option>
									</foreach>
								</select>
								<foreach name="good_list" item="gitem2">
									<input type="hidden" id="good_price_{$gitem2.id}" value="{$gitem2.good_unit_price}" data_vip_good_unit_price="{$gitem2.vip_good_unit_price}" data_good_unit="{$gitem2.good_unit}" data_is_oil="{$gitem2.is_oil}" data_good_name="{$gitem2.good_name}"/>
								</foreach>
								<input type="hidden" id="admin_oil_discount" value="{$admin_oil_discount}">
                                <span class="desc">在商品管理中编辑</span>
							</td>
						</tr>
						<tr>
							<th>商品单价</th>
							<td><input type="text" name="good_unit_price" id="good_unit_price" value="" style="width: 400px" readonly> </td>
						</tr>
                        <tr>
                            <th>价格单位</th>
                            <td><input type="text" name="good_unit" id="good_unit" class="require" value="" style="width: 400px" readonly> </td>
                        </tr>
                        <tr>
                            <th>商品数量</th>
                            <td>
                            	<input type="text" name="good_num" class="require" onchange="change_good_num()" id="good_num" value="" style="width: 400px" placeholder="请输入商品数量">
                            	<span class="desc">加油/加气数量</span>
                            </td>
                        </tr>

						<tr>
							<th>应付总价</th>
							<td>
								<input type="text" name="preprice" id="preprice" value="" style="width: 400px" onchange="change_preprice()">
								<span class="desc">加油/加气的实际费用</span>
							</td>
						</tr>
						<tr>
							<th>优惠金额</th>
							<td><input type="text" name="disprice" id="disprice" value="" style="width: 400px"  readonly> </td>
						</tr>
						<tr>
							<th>实付金额</th>
							<td><input type="text" name="price" id="price" value="" style="width: 400px" readonly> </td>
						</tr>
                        <tr>
                            <th>持卡人姓名</th>
                            <td>
                                <input type="text" class="editable" name="vip_name" id="vip_name" value="" style="width: 400px" placeholder="请输入持卡人姓名" readonly>
                            </td>
                        </tr>
                        <tr>
                            <th>持卡人手机</th>
                            <td>
                                <input type="text" class="editable" name="vip_phone" id="vip_phone" value="" style="width: 400px" placeholder="请输入持卡人手机号" readonly>
                            </td>
                        </tr>
                        <tr>
                            <th>持卡人车牌</th>
                            <td>
                                <input type="text" class="editable" name="vip_plate_number" id="vip_plate_number" value="" style="width: 400px" placeholder="请输入充值汽车的车牌" readonly>
                            </td>
                        </tr>
                        <tr>
                            <th>消费描述</th>
                            <td>
                                <input type="text" name="desc" id="desc" value="" style="width: 400px" placeholder="请输入充值消费描述">
                            </td>
                        </tr>
                    </table>
				</div>

			</div>
			<div class="form-actions">
				<button class="btn btn-primary js-ajax-submit" type="submit">确认付款</button>
				<a class="btn" href="{:U('AdminSale/index')}">返回</a>
			</div>
		</form>
	</div>
	<script type="text/javascript" src="__PUBLIC__/js/common.js"></script>
	<script type="text/javascript" src="__PUBLIC__/js/jquery.barcode.js"></script>
	<script type="text/javascript">
		$(document).delegate(".wrap", "click", function(e) {
	        var ev = e || window.event; // 事件  
	        var target = ev.target || ev.srcElement; // 获得事件源
	        console.log($(target));
	        if ((target.tagName == 'INPUT' || target.tagName == 'SELECT') && target.readonly != true) {
	        }else{
				$('#card_number').select();
	        }
	    });

		$('.editable').click(function(){
            $(this).removeAttr('readonly').select();
        });
        $('.editable').blur(function(){
            $(this).attr('readonly','readonly');
        });

		var card_status = 0;
		$("#card_number").startListen({
			barcodeLen : 10,
			letter : false,
			number : true,
			check  : true,
			show : function(code){
				change_card_id();
			}
		});
		function submitform(){
			if(card_status != 1){
				return false;
			}
			var result = true;
		    $(".require").each(function(){
		        if($(this).val() == ''){
		            var title = $(this).parent().parent().find("th").remove("span").text().replace("*","");
		            alert(title+"不能为空!");
		            result = false;return false;
		        }
		    });
		    if (!result) {
		    	return false;
		    }
		    var card_number = $('#card_number').val();
		    var good_num = $('#good_num').val();
		    var sale_good_id = $('#sale_good_id').val();
			var good_name = $("#good_price_"+sale_good_id).attr('data_good_name');
			var good_unit = $("#good_price_"+sale_good_id).attr('data_good_unit');
		    var preprice = $('#preprice').val();
		    var price = $('#price').val();
		    if (!confirm("是否确认消费？\r\n卡号："+card_number+"\r\n消费商品："+good_name+" "+good_num+good_unit+"\r\n应付金额："+preprice+"\r\n实付金额："+price+"\r\n")) {
		    	return false;
		    }

		    return true;
		}
	</script>
	<script>

		$(document).ready(function () {
			
			$("#card_number").keypress(function (e) { //这里给function一个事件参数命名为e，叫event也行，随意的，e就是IE窗口发生的事件。
				var key = e.which; //e.which是按键的值
				if (key == 13) {
					//change_card_id();
				}
			});
			if(card_status == 1){
				$("#sale_good_id").change(function(){
					change_good_id();
				});
				$("#sale_good_id").trigger('change');
			}else{
				return false;
			}
			// $('.wrap:not(:input)').click(function(){
			// 	console.log($(this));
			// 	$('#card_number').select();
			// 	event.stopPropagation();
			// 	return false;
			// });

		});

		var force_price = false;
		function change_card_id(){
			var card_number = $("#card_number").val();
			$.ajax({url:"{:U('Logistics/AdminCard/ajax_get_card')}",async:false,dataType:"json",data:"card_number="+card_number,type:"post",success:function(t){
				if(t.code == 1){
					var temp = t.data;
					card_status = temp.status;
					if(temp.status != 1){
						alert("该卡号已注销，无法消费!");
					}else{

						$("#card_balance").val(temp.balance);
						$("#logistics_name").val(temp.logistics_name);
						$("#logistics_id").val(temp.id);
						$("#is_vip").val(temp.is_vip);
						/*卡片信息*/
						$("#vip_phone").val(temp.vip_phone);
						$("#vip_name").val(temp.vip_name);
						$("#vip_plate_number").val(temp.vip_plate_number);

						$("#sale_good_id").change(function(){
							change_good_id();
						});
						$("#sale_good_id").trigger('change');

						if (force_price == 'preprice') {
							change_preprice();
						}else{
							change_good_num();
						}
					}

				}else{
					alert(t.data);
				}
			}});
		}

		/*切换商品时的操作*/
		function change_good_id(){
			var sale_good_id = $("#sale_good_id").val();
			var data_good_unit = $("#good_price_"+sale_good_id).attr('data_good_unit');
			var data_good_unit_price = $("#good_price_"+sale_good_id).val();
			var data_vip_good_unit_price = $("#good_price_"+sale_good_id).attr('data_vip_good_unit_price');

			// 设置商品单价
			if ($('#is_vip').val() == '1') {
				$("#good_unit_price").val(data_vip_good_unit_price).addClass('vip');
			}else{
				$("#good_unit_price").val(data_good_unit_price).removeClass('vip');
			}

			// 设置商品单位
			$("#good_unit").val(data_good_unit);

			if (force_price == 'preprice') {
				change_preprice();
			}else{
				change_good_num();
			}
		}

		function floatAdd(arg1,arg2){
		    var r1,r2,m;
		    try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
		    try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
		    m=Math.pow(10,Math.max(r1,r2));
		    return (arg1*m+arg2*m)/m;
		}
		function floatSub(arg1,arg2){
		    var r1,r2,m,n;
		    try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
		    try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
		    m=Math.pow(10,Math.max(r1,r2));
		    //动态控制精度长度
		    return ((arg1*m-arg2*m)/m);
		}
		function floatMul(arg1,arg2){
		    var m=0,s1=arg1.toString(),s2=arg2.toString();
		    try{m+=s1.split(".")[1].length}catch(e){}
		    try{m+=s2.split(".")[1].length}catch(e){}
		    return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m);
		}
		//浮点数除法运算
		function floatDiv(arg1,arg2){
		    var t1=0,t2=0,r1,r2;
		    try{t1=arg1.toString().split(".")[1].length}catch(e){}
		    try{t2=arg2.toString().split(".")[1].length}catch(e){}
		    with(Math){
		        r1=Number(arg1.toString().replace(".",""));
		        r2=Number(arg2.toString().replace(".",""));
		        return (r1/r2)*pow(10,t2-t1);
		    }
		}
		function floatRound(arg,pos){
			arg = parseFloat(arg) * 100;
			arg = Math.round(arg) / 100;
			return arg.toFixed(pos);
		}

		/*更换商品数量*/
		function change_good_num(){
			force_price = 'good_num';
			$('#force_price').val(force_price);
			var card_number = $("#card_number").val();
			var balance = $("#card_balance").val();
			var sale_good_id = $("#sale_good_id").val();
			var data_is_oil = $("#good_price_"+sale_good_id).attr('data_is_oil');
			var good_unit_price = $("#good_unit_price").val();

			if (data_is_oil == 1) {
				var admin_oil_discount = $("#admin_oil_discount").val();
			}else{
				var admin_oil_discount = 0;
			}

			console.log($("#good_num").val());
			var good_num = parseFloat($("#good_num").val());

			good_num = floatRound(good_num,2);
			// 异常数据不进入计算
			if (!good_num || good_num == 'NaN') {$("#good_num").val('');return false;}
			$("#good_num").val(good_num);

			if(sale_good_id == ''){
				alert("请先选择商品!");
				return false;
			}
			
			var disprice = 0;
			var price = 0;
			var preprice = 0;
			var max_good_num = 0;

			// $("button[type=submit]").attr('disabled','disabled').text('计算中...');

			$.post("{:U('Sale/AdminSale/pre_post')}",{good_id: sale_good_id, goods_price: preprice, good_num: good_num, last_key: 'good_num', card_number: card_number},function(result){
				if (result.status == 1) {
					good_num = result.data.good_num;
					price = result.data.price;
					preprice = result.data.goods_price;
					disprice = result.data.dis_price;

					max_good_num = floatDiv(balance, floatSub(good_unit_price, admin_oil_discount));

					if(card_number && parseFloat(price) > parseFloat(balance)){
						alert("余额不足!");
						$("#good_num").val(max_good_num);
						change_good_num();
						return false;
					}else{
						$("#preprice").val(preprice);
						$("#disprice").val(disprice);
						$("#price").val(price);
						return true;
					}
				}else{
					alert(result.info);
				}
				
				// $("button[type=submit]").removeAttr('disabled').text('确认付款');
			}, 'json')
		}

		/*更换商品应付价格*/
		function change_preprice(){
			force_price = 'preprice';
			$('#force_price').val(force_price);
			var card_number = $("#card_number").val();
			var balance = parseFloat($("#card_balance").val());
			var sale_good_id = $("#sale_good_id").val();
			var data_is_oil = $("#good_price_"+sale_good_id).attr('data_is_oil');
			var good_unit_price = $("#good_unit_price").val();
			
			if (data_is_oil == 1) {
				var admin_oil_discount = $("#admin_oil_discount").val();
			}else{
				var admin_oil_discount = 0;
			}

			var preprice = parseFloat($("#preprice").val());
			// 异常数据不进入计算
			if (!preprice || preprice == NaN) {$("#preprice").val('');return false;}

			preprice = floatRound(preprice,2);
			$("#preprice").val(preprice);

			if(!sale_good_id){
				alert("请先选择商品!");
				$("#preprice").val('');
				return false;
			}
			
			var price = 0;
			var disprice = 0;
			var good_num = 0;

			// $("button[type=submit]").attr('disabled','disabled').text('计算中...');

			$.post("{:U('Sale/AdminSale/pre_post')}",{good_id: sale_good_id, goods_price: preprice, good_num: good_num, last_key: 'preprice',card_number: card_number},function(result){
				if (result.status == 1) {
					good_num = result.data.good_num;
					price = result.data.price;
					disprice = result.data.dis_price;

					// 有卡时计算余额，超出时默认设置为最大金额
					if(card_number && parseFloat(price) > parseFloat(balance)){
						good_num = floatRound(floatDiv(balance, floatSub(good_unit_price, admin_oil_discount)),2);
						disprice = floatRound(floatMul(admin_oil_discount, good_num),2);
						max_preprice = floatAdd(balance, disprice);
						alert("由于卡内余额为"+balance+"，最大可用应付金额为"+max_preprice+"!");
						$("#preprice").val(max_preprice);
						change_preprice();
						return false;
					}

					$("#price").val(price);
					$("#disprice").val(disprice);
					$("#good_num").val(good_num);
				}else{
					alert(result.info);
				}

				// $("button[type=submit]").removeAttr('disabled').text('确认付款');
			}, 'json');
		}

		/*更换商品总价格-已不使用*/
		function change_good_price(){
			var card_number = $("#card_number").val();
			var balance = parseFloat($("#card_balance").val());
			var sale_good_id = $("#sale_good_id").val();
			var data_price = $("#good_price_"+sale_good_id).val();
			var data_is_oil = $("#good_price_"+sale_good_id).attr('data_is_oil');
			var good_unit_price = $("#good_unit_price").val();
			
			var admin_oil_discount = $("#admin_oil_discount").val();
			console.log(admin_oil_discount);
			var price = parseFloat($("#price").val());
			price = floatRound(price,2);
			$("#price").val(price);

			if(!sale_good_id){
				alert("请先选择商品!");
				$("#price").val('');
				return false;
			}
			// 有卡时计算余额，超出时默认设置为最大金额
			if(card_number && price > balance){
				alert("最大金额为"+balance+"!");
				$("#price").val(balance);
				change_good_price();
				return false;
			}
			
			var preprice = 0;
			var disprice = 0;
			var good_num = 0;

			if (data_is_oil == 1) {
				good_num = floatRound(floatDiv(price, floatSub(good_unit_price, admin_oil_discount)),2);
				disprice = floatRound(floatMul(admin_oil_discount, good_num),2);
				preprice = floatAdd(price, disprice);
			}else{
				good_num = price;
				disprice = 0;
				preprice = floatAdd(price, disprice);
			}

			$("#preprice").val(preprice);
			$("#disprice").val(disprice);
			$("#good_num").val(good_num);
		}
	</script>
	<script type="text/javascript" src="__PUBLIC__/js/layer3/layer.js"></script>
	<link rel="stylesheet" type="text/css" href="__PUBLIC__/js/layer3/theme/default/layer.css">
	<script type="text/javascript">
		/*此为手动输入*/
		$('.hand_input').click(function(){
		    layer.prompt({title: '请输入口令', formType: 1}, function(pass, index){
		    	if (pass == '24865') {
			    	layer.close(index);
			    	layer.prompt({title: '请填写卡号', formType: 3}, function(text, index){
			        	layer.close(index);
			        	$('#card_number').val(text);
						change_card_id();
			    	});
		    	}else{
			    	layer.close(index);
		        	layer.msg('口令错误');
		    	}
		    });
		});
	</script>
	</body>
</html>